extends Container
class_name DynamicContainer

@export var spacing: int = 5
@export var anim_duration: float = 0.3

var _childrens:Array

func _ready():
	clip_children = Control.CLIP_CHILDREN_ONLY

func _notification(what):
	if what == NOTIFICATION_SORT_CHILDREN:
		_rearrange_children()


func _rearrange_children():
	var valid_children = get_children().filter(func(c): return c.is_visible_in_tree())
	valid_children.reverse()  # 关键修改：反转子节点顺序
	
	# 计算容器最小宽度
	var container_min_width = spacing
	for child in valid_children:
		container_min_width += child.size.x + spacing
	custom_minimum_size.x = container_min_width
		# 从左侧开始排列
	var offset = 0
	for child in valid_children:
		var target_position = Vector2(offset, 0)
		
		# 创建位置动画
		if child.position != target_position:
			var tween = create_tween().set_trans(Tween.TRANS_BACK).set_ease(Tween.EASE_OUT)
			tween.tween_property(child, "position", target_position, anim_duration)
		
		offset += child.size.x + spacing
	
func _update_child_size(child: Control):
	var label: Label = child.get_node("Label")
	var label_size = label.get_minimum_size()
	#child.custom_minimum_size = Vector2(label_size.x + 20, label_size.y + 10)

func _child_entered_tree(child: Node):
	if child is Control:
		child.set_notify_local_transform(true)
		_update_child_size(child)
		child.resized.connect(_on_child_resized.bind(child))
		# 初始位置改为右侧外部
		child.position = Vector2(size.x, 0)
		# 入场动画
		var tween = create_tween()
		tween.tween_property(child, "modulate", Color.WHITE, anim_duration).from(Color.TRANSPARENT)
		queue_sort()
func _child_exiting_tree(child: Node):
	if child is Control:
		var tween = create_tween()
		tween.tween_property(child, "position", child.position + Vector2(-child.size.x, 0), anim_duration)
		tween.parallel().tween_property(child, "modulate", Color.TRANSPARENT, anim_duration)
		tween.tween_callback(child.queue_free)

func _on_child_resized(child: Control):
	_update_child_size(child)
	queue_sort()

# 修正后的add_child方法（不再覆盖原生方法）
func add_custom_child(node: Node):
	super.add_child(node)
	_childrens.push_back(node)
	node.visibility_changed.connect(queue_sort)
	
func remove_back_child():
	if _childrens.is_empty():
		print("没有子弹！")
		return
	
	var target = _childrens.pop_back()
	_child_exiting_tree(target)
	super.remove_child(target)
	
# 修正后的remove_child方法（改为自定义方法）
func remove_custom_child(node: Node):
	_child_exiting_tree(node)
	super.remove_child(node)
